package cn.cloudreal.cbms.statements.action;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.DatadicContext;
import cn.cloudreal.cbms.common.util.PageBean;
import cn.cloudreal.cbms.common.util.StringUtils;
import cn.cloudreal.cbms.statements.service.ProjectPriceService;
import cn.cloudreal.cbms.vo.Dictionary;
import cn.cloudreal.cbms.vo.ProjectPrice;
import cn.cloudreal.cbms.vo.UserInfo;

import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * Title: ITC 项目费用结算
 * </p>
 * <p>
 * Copyright: Copyright (c) 2012
 * </p>
 * <p>
 * Company:云恒瑞通
 * </p>
 * 
 * @author xiayundong
 * @date 2012-8-14
 */
public class ProjectPriceAction extends ActionSupport {

	/**
	 * 
	 */

	private static final long serialVersionUID = 1L;
	/** 日志工具类实例 */
	private static final Logger log = Logger
			.getLogger(ProjectPriceAction.class);

	// service
	ProjectPriceService projectPriceService;

	// list
	private List<ProjectPrice> dataListProjectPrice = null; // 项目费用报表的list
	private List<Dictionary> dataListUserCITY = null; // 归属地市

	// 判断条件
	private String userCity; // 归属地市
	private String type; // 判断是否是初次进入
	private String inputKeyword; // 关键字搜索
	private String startMonth; // 开始月份
	private String endMonth; // 结束月份
	/** 分页对象 */
	PageBean page;
	/** 当前页 */
	int currentPage;

	/**
	 * 列表显示
	 * 
	 * @return
	 */
	public String showProjectPriceList() {
		// 打印进入方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Enter ContractListAction deleteContract() method, return String");
		}
		try {
			getDictionary();
			getUserSession();

			// 初始化分页对象
			page = new PageBean(currentPage == 0 ? 1 : currentPage,
					Constants.PAGE_SIZE);
			if (inputKeyword == null || inputKeyword.equals("")) {
				inputKeyword = "输入媒体名称关键字";
			}
			if (startMonth != null || endMonth != null) {
				try {
					initFactor();
					// 查询
					Map condition = new HashMap();
					condition.put("i_startmonth", startMonth + "-01");
					condition.put("i_endmonth", endMonth + "-01");
					condition.put("i_city", userCity);
					if (inputKeyword == null || inputKeyword.equals("")) {
						condition.put("i_selectkey", "");
						inputKeyword = "输入媒体名称关键字";
					} else {
						if (inputKeyword.equals("输入媒体名称关键字")) {
							condition.put("i_selectkey", "");
						} else {
							condition.put("i_selectkey", inputKeyword);
						}

					}
					System.out.println("inputKeyword=====>" + inputKeyword);
					dataListProjectPrice = projectPriceService
							.getProjectPriceList(condition, page);
				} catch (Exception e) {
					e.printStackTrace();
					return ERROR;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}

		// 打印退出方法体日志
		if (log.isInfoEnabled()) {
			log
					.info("Exit ContractListAction deleteContract() method, return String");
		}
		return SUCCESS;
	}

	// 初始化列表中的条件
	public void initFactor() {
		if (StringUtils.isEmpty(startMonth)) {
			startMonth = "";
		}
		if (StringUtils.isEmpty(endMonth)) {
			endMonth = "";
		}

	}

	// 获取session中的对象
	public void getUserSession() {
		// 获取userSession
		UserInfo userSession = (UserInfo) ServletActionContext.getRequest()
				.getSession().getAttribute("logUser");
		String range = null;
		String cityCode = null;
		range = userSession.getUserRole().getRoleRange() == null ? ""
				: userSession.getUserRole().getRoleRange();
		cityCode = userSession.getUsercity() == null ? "" : userSession
				.getUsercity();
		// 设置权限
		if (null == type) {
			type = "1";
			userCity = cityCode;
		}
		if ("1".equals(range)) {
		} else {
			dataListUserCITY = DatadicContext.getInstance()
					.getDicDataListByCode("CITY");// 归属地市
			dataListUserCITY.clear();
			Dictionary date = DatadicContext.getInstance().getDatadicObject(
					cityCode, "CITY");
			dataListUserCITY.add(date);
			userCity = cityCode;
		}

	}

	/*
	 * 获取字典表中的数据
	 */
	public void getDictionary() {
		dataListUserCITY = DatadicContext.getInstance().getDicDataListByCode(
				"CITY");// 归属地市
		if (dataListUserCITY == null) {
			dataListUserCITY = new ArrayList<Dictionary>();
		}
	}

	/**
	 * 导出表格
	 * 
	 * @return
	 */
	public String exportExcelProjectPrice() {
		try {

			// 获取userSession
			UserInfo userSession = (UserInfo) ServletActionContext.getRequest()
					.getSession().getAttribute("logUser");
			String cityCode = null;
			cityCode = userSession.getUsercity() == null ? "" : userSession
					.getUsercity();
			HttpServletResponse response = ServletActionContext.getResponse();
			if (userCity == null) {
				userCity = cityCode;
			}
			if (inputKeyword == null) {
				inputKeyword = "";
			}
			startMonth = startMonth == null ? "" : startMonth;
			endMonth = endMonth == null ? "" : endMonth;
			inputKeyword = URLDecoder.decode(inputKeyword, "UTF-8");
			if (inputKeyword.equals("输入媒体名称关键字")) {
				inputKeyword = "";
			}
			userCity = URLDecoder.decode(userCity, "UTF-8");
			startMonth = URLDecoder.decode(startMonth, "UTF-8");
			endMonth = URLDecoder.decode(endMonth, "UTF-8");
			String fileExcelName = userCity + "_" + startMonth + "~" + endMonth
					+ "_" + inputKeyword + "_项目费用结算表" + ".xls ";
			try {
				fileExcelName = new String(fileExcelName.getBytes(),
						"iso8859-1");// 解决中文 文件名问题
				response.setHeader("content-disposition",
						"attachment; filename=" + fileExcelName);// 设定输出文件头
				response.setContentType("application/msexcel");// 定义输出类型
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
				return ERROR;
			}

			try {
				OutputStream os = response.getOutputStream();
				WritableWorkbook wwb = Workbook.createWorkbook(os);
				WritableSheet ws = wwb.createSheet("项目费用结算表", 0);
				// ws.setRowView(0, 600); //行高
				ws.setColumnView(0, 8); // 单元格宽度
				for (int i = 1; i < 4; i++) {
					ws.setColumnView(i, 20); // 单元格宽度
				}
				ws.setColumnView(4, 12); // 单元格宽度
				ws.setColumnView(5, 16); // 单元格宽度
				ws.setColumnView(6, 15); // 单元格宽度
				ws.mergeCells(1, 0, 6, 0);// 合并单元格（列、行）第一变量是列，第二变量是行--第三个变量是到第几列，第四变量是行

				WritableFont wtf0 = new WritableFont(WritableFont
						.createFont("宋体"), 16, WritableFont.BOLD, false,
						UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
				WritableCellFormat wcfmt0 = new WritableCellFormat(wtf0);
				// wcfmt0.setBorder(Border.ALL, BorderLineStyle.THIN);
				wcfmt0.setAlignment(jxl.format.Alignment.CENTRE);// 居中
				Label label = new Label(1, 0, userCity + "_" + startMonth + "~"
						+ endMonth + "_" + inputKeyword + "_项目费用结算表", wcfmt0);
				label.setCellFormat(wcfmt0);
				ws.addCell(label);

				WritableFont wfc = new WritableFont(WritableFont
						.createFont("宋体"), 12, WritableFont.BOLD, false,
						UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
				WritableCellFormat wcfFC = new WritableCellFormat(wfc);
				wcfFC.setBorder(Border.ALL, BorderLineStyle.THIN);
				WritableFont wfc1 = new WritableFont(WritableFont
						.createFont("宋体"), 11, WritableFont.NO_BOLD, false,
						UnderlineStyle.NO_UNDERLINE, Colour.BLACK);

				WritableCellFormat wcfFC1 = new WritableCellFormat(wfc1);
				wcfFC1.setBorder(Border.ALL, BorderLineStyle.THIN);

				Label label1 = new Label(1, 1, "项目名称", wcfFC);
				ws.addCell(label1);
				Label label2 = new Label(2, 1, "媒体名称", wcfFC);
				ws.addCell(label2);
				Label label3 = new Label(3, 1, "合同编号", wcfFC);
				ws.addCell(label3);
				Label label4 = new Label(4, 1, "费用类型", wcfFC);
				ws.addCell(label4);
				Label label5 = new Label(5, 1, "费用子类", wcfFC);
				ws.addCell(label5);
				Label label6 = new Label(6, 1, "结算金额", wcfFC);
				ws.addCell(label6);

				// 查询
				Map condition = new HashMap();
				condition.put("i_startmonth", startMonth + "-01");
				condition.put("i_endmonth", endMonth + "-01");
				condition.put("i_city", userCity);
				if (inputKeyword != null) {
					if (inputKeyword.equals("输入媒体名称关键字")) {
						condition.put("i_selectkey", "");
					} else {
						condition.put("i_selectkey", inputKeyword);
					}
				}

				// 所有项目费用结算数据
				dataListProjectPrice = projectPriceService
						.getTotalProjectPriceList(condition);
				if (dataListProjectPrice != null
						&& dataListProjectPrice.size() > 0) {
					for (int i = 0; i < dataListProjectPrice.size(); i++) {
						String projectName = dataListProjectPrice.get(i)
								.getProjectName();
						if (projectName.equals("本页合计")) {
							dataListProjectPrice.remove(i);
						}
					}

					// 项目名称
					for (int i = 0; i < dataListProjectPrice.size(); i++) {
						Label upLimitNum1 = new Label(1, i + 2,
								dataListProjectPrice.get(i).getProjectName(),
								wcfFC1);
						ws.addCell(upLimitNum1);
					}
					// 媒体名称
					for (int i = 0; i < dataListProjectPrice.size(); i++) {
						Label upLimitNum2 = new Label(2, i + 2,
								dataListProjectPrice.get(i).getMediaName(),
								wcfFC1);
						ws.addCell(upLimitNum2);
					}
					// 合同编号
					for (int i = 0; i < dataListProjectPrice.size(); i++) {
						Label upLimitNum3 = new Label(3, i + 2,
								dataListProjectPrice.get(i).getContractID(),
								wcfFC1);
						ws.addCell(upLimitNum3);
					}
					// 费用类型
					for (int i = 0; i < dataListProjectPrice.size(); i++) {
						Label upLimitNum4 = new Label(4, i + 2,
								dataListProjectPrice.get(i).getCostTypeName(),
								wcfFC1);
						ws.addCell(upLimitNum4);
					}
					// 费用子类
					for (int i = 0; i < dataListProjectPrice.size(); i++) {
						Label upLimitNum5 = new Label(5, i + 2,
								dataListProjectPrice.get(i)
										.getCostSubTypeName(), wcfFC1);
						ws.addCell(upLimitNum5);
					}
					// 结算金额
					for (int i = 0; i < dataListProjectPrice.size(); i++) {
						// Number upLimitNum6 = new Number(6, i+2,
						// dataListProjectPrice.get(i).getFundAmount());
						Label upLimitNum6 = new Label(6, i + 2, ""
								+ dataListProjectPrice.get(i).getFundAmount(),
								wcfFC1);
						ws.addCell(upLimitNum6);
					}
				}
				wwb.write();
				wwb.close();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
				return ERROR;
			} catch (RowsExceededException e) {
				e.printStackTrace();
				return ERROR;
			} catch (WriteException e) {
				e.printStackTrace();
				return ERROR;
			} catch (Exception e) {
				e.printStackTrace();
				return ERROR;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return null;
	}

	/**
	 * set/get方法
	 */
	public ProjectPriceService getProjectPriceService() {
		return projectPriceService;
	}

	public void setProjectPriceService(ProjectPriceService projectPriceService) {
		this.projectPriceService = projectPriceService;
	}

	public List<Dictionary> getDataListUserCITY() {
		return dataListUserCITY;
	}

	public void setDataListUserCITY(List<Dictionary> dataListUserCITY) {
		this.dataListUserCITY = dataListUserCITY;
	}

	public String getUserCity() {
		return userCity;
	}

	public void setUserCity(String userCity) {
		this.userCity = userCity;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public List<ProjectPrice> getDataListProjectPrice() {
		return dataListProjectPrice;
	}

	public void setDataListProjectPrice(List<ProjectPrice> dataListProjectPrice) {
		this.dataListProjectPrice = dataListProjectPrice;
	}

	public PageBean getPage() {
		return page;
	}

	public void setPage(PageBean page) {
		this.page = page;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public String getInputKeyword() {
		return inputKeyword;
	}

	public void setInputKeyword(String inputKeyword) {
		this.inputKeyword = inputKeyword;
	}

	public String getStartMonth() {
		return startMonth;
	}

	public void setStartMonth(String startMonth) {
		this.startMonth = startMonth;
	}

	public String getEndMonth() {
		return endMonth;
	}

	public void setEndMonth(String endMonth) {
		this.endMonth = endMonth;
	}

}
